﻿using Com.EnuoCms.Model.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EnuoSoft.CodeGenerator
{
    class Program
    {
        //private static string[] gettemplates()
        //{
        //    string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template");
        //    System.IO.DirectoryInfo d = new DirectoryInfo(path);
        //    List<string> names = new List<string>();
        //    foreach (var item in d.GetFiles())
        //    {
        //        if (item.Extension == "txt") {
        //            names.Add(item.Name);
        //        }
        //    }
        //    return names.ToArray();

        //   // return  new string[] {
        //   // "DataContex.txt",
        //   // "ModelRepositorye.txt",
        //   // "ModelCommand.txt",
        //   // "ModelHandler.txt",
        //   // "Controller.txt",
        //   // "Model.txt",
        //   // "OpModel.txt"
        //   //};
        //}

       
        //static string getTemplateFolder()
        //{
        //    string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OutPut");
        //    System.IO.DirectoryInfo d = new DirectoryInfo(path);
        //    if (!d.Exists) { d.Create(); }
        //    return path;
        //}

        static void Main(string[] args)
        {
            string[] types = getEntitiesType();
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template");
            System.IO.DirectoryInfo d = new DirectoryInfo(path);
            foreach (var folder in d.GetDirectories())
            {
                foreach (string element in types)
                {
                    Console.WriteLine(element + ", gener...");
                    foreach (var file in folder.GetFiles())
                    {
                        Console.WriteLine(".... .... " + file.Name);
                        generCodeFromTemplate(element, file.FullName);
                        Console.WriteLine("");
                    }
                }
            }
            generEnuoCmsDataContex(types, path);
            Console.WriteLine("Success!");
            Console.ReadLine();
        }

        private static void generEnuoCmsDataContex(string[] types, string directory)
        {
            StringBuilder dbSets = new StringBuilder();
            //StringBuilder modelBinds = new StringBuilder();

            foreach (string type in types)
            {
                dbSets.Append(string.Format("        public DbSet<{0}> {0}Set {{ get; set; }}\r\n", type));
                //modelBinds.Append(string.Format("            modelBuilder.Entity<{0}>().ToTable(\"{0}\");\r\n", type));
            }

            string templatePath = System.IO.Path.Combine(directory, "EnuoCmsDataContex.txt");
            string templateContent = loadTemplate(templatePath);

            string codeContent = templateContent
                .Replace("{0}", dbSets.ToString());

            string codepath = templatePath.Replace("/Template/", "/OutPut/").Replace(".txt", ".cs");
            writeFile(codepath, codeContent);
        }

        private static string loadTemplate(string templatePath)
        {
            FileStream fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read);

            StreamReader reader = new StreamReader(fs);
            string content = reader.ReadToEnd();
            reader.Close();

            fs.Close();

            return content;
        }

        private static void generCodeFromTemplate(string type, string templatePath)
        {
            string templateContent = loadTemplate(templatePath);
            string codeContent = templateContent.Replace("{0}", type);
            string codepath = templatePath.Replace("/Template/", "/OutPut/"+type+"/").Replace("/M_", "/"+type).Replace(".txt", ".cs");
            writeFile(codepath, codeContent);
        }

        private static void writeFile(string codepath, string content)
        {
            content = @"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by zhanxp@me.com
//
//     If any question, please let's know.
//     It's a great help for improve our templates
// </auto-generated>
//------------------------------------------------------------------------------

" + content;

            FileInfo file = new FileInfo(codepath);
            if (file.Exists)
            {
                file.Delete();
            }

            if (!file.Directory.Exists) {
                file.Directory.Create();
            }

            FileStream fs = file.Create();

            StreamWriter writer = new StreamWriter(fs);
            writer.Write(content);
            writer.Close();

            fs.Close();
        }

        private static string[] getEntitiesType()
        {
            Type[] types = typeof(Admin).Assembly.GetTypes();

            var typeNames = from type in types
                            where type.FullName.Contains("Com.EnuoCms.Model.Entities")
                            select type.Name;

            return typeNames.ToArray();
        }
    }
}
